layui.use(['jquery', 'layer'], function(){
    var $ = layui.$;
    var layer = layui.layer;
    
    // 初始化考试数据
    var record = JSON.parse('<?= json_encode($record) ?>');
    var paper = JSON.parse('<?= json_encode($paper) ?>');
    var answers = record.answers ? JSON.parse(record.answers) : {};
    var questions = [];
    var currentIndex = 0;
    
    // 获取题目数据
    $.ajax({
        url: '/question/list',
        type: 'GET',
        data: {ids: paper.question_ids},
        async: false,
        success: function(res){
            questions = res.data;
        }
    });
    
    // 初始化界面
    $('#paperTitle').text(paper.title);
    renderQuestion(0);
    startTimer();
    
    // 渲染题目
    function renderQuestion(index) {
        var q = questions[index];
        var html = `<div class="question-item" data-id="${q.id}">
            <div class="question-title">${index+1}. ${q.content}</div>`;
        
        if (q.image) {
            html += `<div class="question-image"><img src="${q.image}"></div>`;
        }
        
        switch(q.type) {
            case 1: // 填空
                html += `<input type="text" class="layui-input answer-input" 
                          value="${answers[q.id] || ''}">`;
                break;
            case 2: // 单选
            case 3: // 多选
                var options = JSON.parse(q.options);
                options.forEach(opt => {
                    var checked = (answers[q.id] && answers[q.id].includes(opt.id)) ? 'checked' : '';
                    html += `<div class="option-item">
                        <input type="${q.type==2?'radio':'checkbox'}" name="q_${q.id}" 
                               value="${opt.id}" ${checked}>
                        <span>${opt.text}</span>
                        ${opt.image ? `<img src="${opt.image}">` : ''}
                    </div>`;
                });
                break;
            case 4: // 判断
                html += `<div class="option-item">
                    <input type="radio" name="q_${q.id}" value="1" ${answers[q.id]=='1'?'checked':''}> 正确
                </div>
                <div class="option-item">
                    <input type="radio" name="q_${q.id}" value="0" ${answers[q.id]=='0'?'checked':''}> 错误
                </div>`;
                break;
            case 5: // 简答
                html += `<textarea class="layui-textarea answer-textarea">${answers[q.id] || ''}</textarea>`;
        }
        
        html += '</div>';
        $('#questionContainer').html(html);
        currentIndex = index;
    }
    
    // 保存当前答案
    function saveAnswer() {
        var q = questions[currentIndex];
        var answer = '';
        
        switch(q.type) {
            case 1:
                answer = $('.answer-input').val().trim();
                break;
            case 2:
                answer = $(`input[name=q_${q.id}]:checked`).val() || '';
                break;
            case 3:
                answer = [];
                $(`input[name=q_${q.id}]:checked`).each(function(){
                    answer.push($(this).val());
                });
                break;
            case 4:
                answer = $(`input[name=q_${q.id}]:checked`).val() || '';
                break;
            case 5:
                answer = $('.answer-textarea').val().trim();
        }
        
        if (answer) answers[q.id] = answer;
    }
    
    // 倒计时
    function startTimer() {
        var duration = paper.duration * 60;
        var timer = setInterval(function(){
            duration--;
            var h = Math.floor(duration / 3600);
            var m = Math.floor((duration % 3600) / 60);
            var s = duration % 60;
            
            $('#countdown').text(
                `${h.toString().padStart(2,'0')}:${m.toString().padStart(2,'0')}:${s.toString().padStart(2,'0')}`
            );
            
            if (duration <= 0) {
                clearInterval(timer);
                submitExam();
            }
        }, 1000);
    }
    
    // 提交考试
    function submitExam() {
        saveAnswer();
        
        $.ajax({
            url: '/exam/submit',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                record_id: record.id,
                answers: answers
            }),
            success: function(res){
                if (res.code === 0) {
                    layer.msg('提交成功! 得分: ' + res.score);
                    setTimeout(function(){ location.href = '/exam/result'; }, 2000);
                } else {
                    layer.msg(res.msg);
                }
            }
        });
    }
    
    // 事件绑定
    $('#prevBtn').click(function(){
        if (currentIndex > 0) {
            saveAnswer();
            renderQuestion(currentIndex - 1);
        }
    });
    
    $('#nextBtn').click(function(){
        saveAnswer();
        
        // 练习模式实时判断
        if (paper.mode == 1) {
            var q = questions[currentIndex];
            var correct = checkAnswer(q, answers[q.id]);
            layer.msg(correct ? '回答正确!' : '回答错误!');
        }
        
        if (currentIndex < questions.length - 1) {
            renderQuestion(currentIndex + 1);
        }
    });
    
    $('#submitBtn').click(function(){
        layer.confirm('确定要提交试卷吗?', function(){
            submitExam();
        });
    });
});